package server

import (
	"gorm.io/gorm"

	address2 "gitee.com/enjoy_5/enjoy-wallet/proto/address"

	"gitee.com/enjoy_5/enjoy-wallet/model/address"
)

func AddressPbToModel(in *address2.AddressInfo) *address.Address {
	return &address.Address{
		Model: gorm.Model{
			ID: uint(in.Id),
		},
		UserID:          in.GetUserid(),
		ConsigneeName:   in.ConsigneeName,
		Mobile:          in.GetMobile(),
		Area:            in.GetArea(),
		DetailedAddress: in.GetDetailedAddress(),
		Tag:             int64(in.GetTag()),
		DefaultAddress:  in.GetDefaultAddress(),
	}
}

func AddressModelToPb(in *address.Address) *address2.AddressInfo {
	return &address2.AddressInfo{
		Id:              int64(in.ID),
		Userid:          in.UserID,
		ConsigneeName:   in.ConsigneeName,
		Mobile:          in.Mobile,
		Area:            in.Area,
		DetailedAddress: in.DetailedAddress,
		Tag:             address2.TagType(in.Tag),
		DefaultAddress:  in.DefaultAddress,
	}
}

func CreateAddress(in *address2.AddressInfo) (*address2.AddressInfo, error) {
	mod := AddressPbToModel(in)
	res, err := mod.CreateAddress()
	if err != nil {
		return nil, err
	}

	return AddressModelToPb(res), nil
}

func UpdateAddress(in *address2.AddressInfo) (*address2.AddressInfo, error) {
	res, err := AddressPbToModel(in).UpdateAddress(in.Userid)
	return AddressModelToPb(res), err
}

func DeleteAddress(in *address2.DeleteAddressRequest) error {
	a := address.Address{
		UserID: in.GetUserID(),
	}

	err := a.DeleteAddress()
	if err != nil {
		return err
	}

	return a.DeleteAddress()
}
